<template>
  <div>
    <cube-page :title="title" :showBackButton="true" />
    <div class="view-wrapper">
      <cube-scroll
        ref="scroll"
        :scroll-events="['scroll']"
        :options="options"
        @scroll="onScrollHandle"
        @pulling-down="onPullingDown"
        @pulling-up="onPullingUp"
        nest-mode="native"
      >
        <ul class="list_ul cube-scroll-list">
          <li
            class="list_li"
            v-for="(item, index) in courseLiveLists"
            :key="index"
          >
            <!-- <router-link :to="{ path: '/course', query: { course: item } }"> -->
            <div @click="jumpToLiveCourse(item)">
              <div class="image-con l">
                <img :src="item.thumb" :onerror="noImage" />
                <!-- <div class="live"></div> -->
              </div>
              <div class="text-con l">
                <div class="title">{{ item.title }}</div>
                <div class="desc">
                  {{ item.author }}
                  <!-- <span class="dot">·</span>
                  {{ item.courseName }} -->
                  <span
                    :class="getCourseStatusClass(item.status)"
                    v-if="item.status != 'PENDING'"
                    >{{ item.status | statusFilter }}</span
                  >
                </div>
                <div class="user-info">
                  时间：{{ item.startTime | dateFormat("yyyy-MM-dd hh:mm") }} ~
                  {{ item.endTime | dateFormat("hh:mm") }}
                </div>
              </div>
            </div>
            <!-- </router-link> -->
          </li>
        </ul>

        <ul class="list_ul cube-scroll-list">
          <li
            class="list_li"
            v-for="(item, index) in courseVodLists"
            :key="index"
          >
            <!-- <router-link :to="{ path: '/course', query: { course: item } }"> -->
            <div @click="jumpToCourse(item)">
              <div class="image-con l">
                <img :src="item.thumb" :onerror="noImage" />
                <div class="live" v-if="0">直播</div>
              </div>
              <div class="text-con l">
                <div class="title">{{ item.title }}</div>
                <div class="desc">
                  {{ item.author }}
                </div>
                <div class="user-info">进度：{{ item.progress }}%</div>
              </div>
            </div>
            <!-- </router-link> -->
          </li>
        </ul>

        <template slot="pulldown" slot-scope="props">
          <div
            v-if="props.pullDownRefresh"
            class="cube-pulldown-wrapper"
            :style="pullDownStyle"
          >
            <div class="pulldown-content">
              <span v-if="props.beforePullDown">{{ pullDownTip }}</span>
              <template v-else>
                <span v-if="props.isPullingDown">正在更新...</span>
                <span v-else>更新成功</span>
              </template>
            </div>
          </div>
        </template>
      </cube-scroll>
    </div>
  </div>
</template>

<script>
import CubePage from "../components/cube-page.vue";
import { getLiveCourseList, getCourseList } from "../api/course";
import { MessageKey, EventManager, enterRoom, setCurrentCourse } from "../api/message";
import coursestatus from "../enum/coursestatus";

export default {
  components: {
    CubePage
  },
  data() {
    return {
      title: "直播课程",
      pageIndex: 1,
      pageSize: 10,
      selectedItem: null,
      courseLiveLists: [],
      courseVodLists: [],
      options: {
        pullDownRefresh: {
          threshold: 40,
          stop: 40,
          txt: "更新成功"
        },
        pullUpLoad: true
      },
      pullDownTip: this.getPullDownTip(),
      pullDownStyle: "top:-30px",
      noImage: 'this.src="' + require("@/assets/icon_no_image.png") + '"'
    };
  },
  created() {
    if (this.$route.params.isLive != null) {
      self.courseMoreIsLive = this.$route.params.isLive;
    } else {
      this.$route.params.isLive = self.courseMoreIsLive;
    }
    this.title = this.$route.params.isLive ? "直播课程" : "点播课程";
    this.registerEvent();
    this.refreshData();
    if (!self.currentAudioContext) {
      self.currentAudioContext = new (window.AudioContext ||
        window.webkitAudioContext)();
    }
  },
  computed: {},
  methods: {
    onScrollHandle(pos) {
      this.pullDownY = pos.y;
      this.pullDownTip = this.getPullDownTip();
      if (pos.y > 0) {
        this.pullDownStyle = `top:${pos.y - 20}px`;
        this.triggerSurpriseFlag = false;
        if (this.pullDownY >= this.options.pullDownRefresh.threshold) {
          this.triggerSurpriseFlag = true;
        }
      }
    },
    onPullingDown() {
      if (this.triggerSurpriseFlag) {
        this.triggerSurprise = true;
        this.refreshData();
        return;
      }
      setTimeout(() => {
        this.pullFinish();
      }, 1000);
    },
    onPullingUp() {
      setTimeout(() => {
        this.loadMoreData();
      }, 1000);
    },
    pullFinish() {
      this.$refs.scroll.forceUpdate();
    },
    getPullDownTip() {
      if (
        this.options &&
        this.pullDownY <= this.options.pullDownRefresh.threshold
      ) {
        return "下拉刷新";
      } else {
        return "释放刷新";
      }
    },
    refreshData() {
      this.pageIndex = 1;
      if (this.$route.params.isLive) {
        getLiveCourseList(this.pageIndex, this.pageSize)
          .then(response => {
            console.log(response);
            this.courseLiveLists = response.data;
            this.pullFinish();
          })
          .catch(error => {
            console.log(error);
          });
      } else {
        getCourseList(this.pageIndex, this.pageSize)
          .then(response => {
            console.log(response);
            this.courseVodLists = response.data;
            this.pullFinish();
          })
          .catch(error => {
            console.log(error);
            this.$toastErrorCode(error);
          });
      }
    },
    loadMoreData() {
      let pageIndex = this.pageIndex + 1;
      if (this.$route.params.isLive) {
        getLiveCourseList(pageIndex, this.pageSize)
          .then(response => {
            this.pageIndex = pageIndex;
            console.log(response);
            response.data.forEach(item => {
              this.courseLiveLists.push(item);
            });
            this.pullFinish();
          })
          .catch(error => {
            console.log(error);
            this.$toastErrorCode(error);
          });
      } else {
        getCourseList(this.pageIndex, this.pageSize)
          .then(response => {
            this.pageIndex = pageIndex;
            console.log(response);
            response.data.forEach(item => {
              this.courseVodLists.push(item);
            });
            this.pullFinish();
          })
          .catch(error => {
            console.log(error);
            this.$toastErrorCode(error);
          });
      }
    },
    getCourseStatusClass(value) {
      if (!value) return "";

      let result = "";
      switch (value) {
        case coursestatus.kCOURSE_STATUS_PLAYING:
          result = "PLAYING";
          break;
        case coursestatus.kCOURSE_STATUS_READY:
          // result = "READY";
          result = "PLAYING";
          break;
        case coursestatus.kCOURSE_STATUS_PENDING:
          result = "PENDING";
          break;
        case coursestatus.kCOURSE_STATUS_UPLOADED:
          result = "UPLOADED";
          break;
        case coursestatus.kCOURSE_STATUS_END:
          result = "END";
          break;
        case coursestatus.kCOURSE_STATUS_CANCEL:
          result = "CANCEL";
          break;
        default:
          break;
      }
      return result.toLowerCase();
    },
    jumpToCourse(item) {
      if (self.currentAudioContext.state === "suspended") {
        self.currentAudioContext.resume();
      }
      this.$router.push({ path: "/course", query: { course: item } });
    },
    jumpToLiveCourse(item) {
      if (!this.$route.params.isLive) {
        this.jumpToCourse(item);
        return;
      }

      if (self.currentAudioContext.state === "suspended") {
        self.currentAudioContext.resume();
      }

      item.signCount = 1;
      this.selectedItem = item;
      setCurrentCourse(this.selectedItem);
      enterRoom(item.id);
    },
    enterRoomSuccess() {
      this.jumpToCourse(this.selectedItem);
    },
    registerEvent() {
      EventManager.Register(
        MessageKey.enterRoom,
        this.enterRoomSuccess.bind(this),
        this
      );
      this.$once("hook:beforeDestroy", () => {
        EventManager.UnRegister(MessageKey.enterRoom, this);
      });
    }
  },
  filters: {
    statusFilter: function(value) {
      if (!value) return "";

      let result = "";
      switch (value) {
        case coursestatus.kCOURSE_STATUS_UPLOADED:
        case coursestatus.kCOURSE_STATUS_END:
          result = "已结束";
          break;
        case coursestatus.kCOURSE_STATUS_PLAYING:
        case coursestatus.kCOURSE_STATUS_READY:
          result = "正在直播";
          break;
        default:
          break;
      }
      return result;
    }
  }
};
</script>

<style lang="stylus" scoped>
.view-wrapper {
  position: fixed;
  top: 44px;
  left: 0;
  bottom: 0px;
  width: 100%;

  .index-list-wrapper {
    height: 100%;
    width: 100%;
    margin: 0 auto;
    overflow: hidden;
  }
}

.pulldown-content {
  font-size: 14px;
}

.list_ul {
  display: flex;
  flex-wrap: wrap;

  .list_li {
    width: 100%;
    padding: 10px;

    img {
      width: 100%;
    }

    .label {
      font-size: 14px;
      padding-bottom: 10px;
    }

    .image-con {
      width: 28%;
    }

    .text-con {
      width: 68.5%;
      padding-left: 10px;
    }

    .l {
      position: relative;
      float: left;
    }

    .live {
      background-image: linear-gradient(131deg, #f92d2d 0, #f01414 100%);
      position: absolute;
      color: #FFF;
      border: 2px solid #FFF;
      border-radius: 5px;
      padding: 2px;
      font-size: 12px;
      top: 2px;
      right: 10px;
    }

    .title {
      font-size: 16px;
      line-height: 20px;
      color: #2B333B;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      word-break: break-all;
      text-align: left;
    }

    .desc {
      padding: 5px;
      font-size: 12px;
      line-height: 12px;
      border-radius: 5px;
      color: #2B333B;
      background: rgba(0, 0, 0, 0.04);
      text-align: left;
      margin: 4px 0px 8px 0px;

    .ready {
        float: right;
        font-size: 10px;
        font-weight: normal;
        color: #00a65a;
        border: 1px solid #00a65a;
        border-radius: 3px;
        padding: 2px 2px;
        margin-top: -3px;
        position: absolute;
        right: 5px;
    }
      .playing {
        float: right;
        font-size: 10px;
        font-weight: normal;
        color: #f92d2d;
        border: 1px solid #f92d2d;
        border-radius: 3px;
        padding: 2px 2px;
        margin-top: -3px;
        position: absolute;
        right: 5px;
      }

      .uploaded {
        float: right;
        font-size: 10px;
        font-weight: normal;
        color: #777;
        border: 1px solid #777;
        border-radius: 3px;
        padding: 2px 2px;
        margin-top: -3px;
        position: absolute;
        right: 5px;
      }

      .end {
        float: right;
        font-size: 10px;
        font-weight: normal;
        color: #777;
        border: 1px solid #777;
        border-radius: 3px;
        padding: 2px 2px;
        margin-top: -3px;
        position: absolute;
        right: 5px;
      }
    }

    .user-info {
      font-size: 12px;
      line-height: 12px;
      color: #333;
      text-align: left;
    }

    .hide {
      display: none;
    }
  }
}
</style>
